package com.smsc.headend.connector.utils;

import gurux.dlms.GXDLMSTranslator;
import gurux.dlms.TranslatorOutputType;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CosemXMLUtil {

    public static final GXDLMSTranslator  translator = new GXDLMSTranslator(TranslatorOutputType.SIMPLE_XML);

    public static String getExceptionResponse(String resultXml) {
        Pattern pattern1 = Pattern.compile("ServiceError.*Value=\"(.*)\"");
        Matcher m1 = pattern1.matcher(resultXml);
        Pattern pattern2 = Pattern.compile("StateError.*Value=\"(.*)\"");
        Matcher m2 = pattern2.matcher(resultXml);
        StringBuilder sb = new StringBuilder();
        if (m1.find()) {
            sb.append(m1.group(1));
        }
        sb.append(":");
        if (m2.find()) {
            String stateError = m2.group(1);
            sb.append(stateError);
        }
        return sb.toString();
    }

    public static  String getResponseType(String resultXml) {
        Pattern pattern = Pattern.compile("<PDU>[\t\r\n.]*<(.*)>");
        Matcher matcher = pattern.matcher(resultXml);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }

    public static String getDataAccessCode(String resultString) {
        Pattern pattern = Pattern.compile("DataAccessError.*Value=\"(.*)\"");
        Matcher m = pattern.matcher(resultString);
        if (m.find()) {
            return m.group(1);
        }
        Pattern pattern2 = Pattern.compile("Result.*Value=\"(.*)\"");
        Matcher m2 = pattern2.matcher(resultString);
        if (m2.find()) {
            return m2.group(1);
        }
        return null;
    }

    public static String getHdlcDataResult(String resultString) {
        Pattern ptHdlc = Pattern.compile("(?<=<Data>)(?:(?!</Data>).)*", Pattern.DOTALL);
        Matcher mHdlc = ptHdlc.matcher(resultString);
        if (mHdlc.find()) {
            return mHdlc.group().replace("\r", "").replace("\n", "").replaceAll("  ", "");
        }

        return null;
    }

    public static String getAssociationResult(String resultString) {
        Pattern pattern = Pattern.compile("AssociationResult.*Value=\"(.*)\"");
        Matcher m = pattern.matcher(resultString);
        if (m.find()) {
            return m.group(1);
        }
        return null;
    }

}
